const axios = require('axios');
const config = require('@/config/default');

class WeatherController {
    constructor() {
        // 高德地图天气API配置
        this.apiKey = config.amap.apiKey;
        this.baseUrl = config.amap.weatherApiUrl;
    }

    /**
     * 查询城市天气信息
     * @param {string} city - 城市名称
     * @returns {Object} 天气查询结果
     */
    async getWeatherInfo(city) {
        try {
            console.log(`查询天气信息: ${city}`);

            // 构建请求参数
            const params = {
                key: this.apiKey,
                city: city,
                extensions: 'all' // 返回预报天气
            };

            // 发送请求到高德地图天气API
            const response = await axios.get(this.baseUrl, {
                params: params,
                timeout: 10000 // 10秒超时
            });

            console.log('高德天气API响应:', JSON.stringify(response.data));

            // 检查API响应状态
            if (response.data.status !== '1') {
                throw new Error(`天气API调用失败: ${response.data.info || '未知错误'}`);
            }

            // 解析天气数据
            const weatherData = this.parseWeatherData(response.data, city);

            return {
                success: true,
                data: weatherData,
                message: `成功获取${city}的天气信息`
            };

        } catch (error) {
            console.error('天气查询失败:', error);
            
            // 如果是网络错误或API错误，返回友好的错误信息
            let errorMessage = '天气查询失败，请稍后再试';
            
            if (error.response) {
                // API返回了错误响应
                errorMessage = `天气服务暂时不可用: ${error.response.status}`;
            } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
                // 网络连接问题
                errorMessage = '网络连接失败，请检查网络设置';
            } else if (error.message.includes('天气API调用失败')) {
                // API业务错误
                errorMessage = error.message;
            }

            return {
                success: false,
                message: errorMessage,
                data: null
            };
        }
    }

    /**
     * 解析高德地图天气API返回的数据
     * @param {Object} apiData - API返回的原始数据
     * @param {string} city - 城市名称
     * @returns {Object} 格式化的天气数据
     */
    parseWeatherData(apiData, city) {
        try {
            const lives = apiData.lives || [];
            const forecasts = apiData.forecasts || [];

            // 实时天气数据
            let currentWeather = null;
            if (lives.length > 0) {
                const live = lives[0];
                currentWeather = {
                    city: live.city || city,
                    adcode: live.adcode,
                    province: live.province,
                    reporttime: live.reporttime,
                    weather: live.weather,
                    temperature: live.temperature,
                    winddirection: live.winddirection,
                    windpower: live.windpower,
                    humidity: live.humidity,
                    temperature_float: live.temperature_float,
                    humidity_float: live.humidity_float
                };
            }

            // 预报天气数据
            let forecastWeather = [];
            if (forecasts.length > 0) {
                const forecast = forecasts[0];
                forecastWeather = (forecast.casts || []).map(cast => ({
                    date: cast.date,
                    week: cast.week,
                    dayweather: cast.dayweather,
                    nightweather: cast.nightweather,
                    daytemp: cast.daytemp,
                    nighttemp: cast.nighttemp,
                    daywind: cast.daywind,
                    nightwind: cast.nightwind,
                    daypower: cast.daypower,
                    nightpower: cast.nightpower,
                    daytemp_float: cast.daytemp_float,
                    nighttemp_float: cast.nighttemp_float
                }));
            }

            return {
                city: city,
                current: currentWeather,
                forecast: forecastWeather,
                updateTime: new Date().toISOString()
            };

        } catch (error) {
            console.error('解析天气数据失败:', error);
            throw new Error('天气数据解析失败');
        }
    }

    /**
     * 格式化天气信息为用户友好的文本
     * @param {Object} weatherData - 天气数据
     * @returns {string} 格式化的天气描述
     */
    formatWeatherText(weatherData) {
        try {
            let weatherText = `📍 ${weatherData.city}天气信息\n\n`;

            // 实时天气
            if (weatherData.current) {
                const current = weatherData.current;
                weatherText += `🌡️ 实时天气：\n`;
                weatherText += `   天气：${current.weather}\n`;
                weatherText += `   温度：${current.temperature}°C\n`;
                weatherText += `   湿度：${current.humidity}%\n`;
                weatherText += `   风向：${current.winddirection}\n`;
                weatherText += `   风力：${current.windpower}级\n`;
                weatherText += `   更新时间：${current.reporttime}\n\n`;
            }

            // 预报天气
            if (weatherData.forecast && weatherData.forecast.length > 0) {
                weatherText += `📅 未来天气预报：\n`;
                weatherData.forecast.slice(0, 3).forEach((forecast, index) => {
                    const dayLabel = index === 0 ? '今天' : index === 1 ? '明天' : '后天';
                    weatherText += `   ${dayLabel}(${forecast.date})：\n`;
                    weatherText += `     白天：${forecast.dayweather} ${forecast.daytemp}°C ${forecast.daywind}${forecast.daypower}级\n`;
                    weatherText += `     夜间：${forecast.nightweather} ${forecast.nighttemp}°C ${forecast.nightwind}${forecast.nightpower}级\n`;
                });
            }

            return weatherText;

        } catch (error) {
            console.error('格式化天气文本失败:', error);
            return '天气信息格式化失败，请稍后再试';
        }
    }

    /**
     * 生成天气建议
     * @param {Object} weatherData - 天气数据
     * @returns {string} 天气建议文本
     */
    generateWeatherAdvice(weatherData) {
        try {
            let advice = '\n💡 出行建议：\n';

            if (weatherData.current) {
                const temp = parseInt(weatherData.current.temperature);
                const weather = weatherData.current.weather;
                const humidity = parseInt(weatherData.current.humidity);

                // 温度建议
                if (temp <= 0) {
                    advice += '   🧥 天气严寒，请注意保暖，建议穿厚羽绒服\n';
                } else if (temp <= 10) {
                    advice += '   🧥 天气较冷，建议穿厚外套或毛衣\n';
                } else if (temp <= 20) {
                    advice += '   👕 天气凉爽，建议穿薄外套或长袖\n';
                } else if (temp <= 30) {
                    advice += '   👕 天气温暖，建议穿轻薄衣物\n';
                } else {
                    advice += '   🌡️ 天气炎热，建议穿透气轻薄衣物，注意防暑\n';
                }

                // 天气状况建议
                if (weather.includes('雨')) {
                    advice += '   ☔ 有降雨，请携带雨具\n';
                } else if (weather.includes('雪')) {
                    advice += '   ❄️ 有降雪，注意路面湿滑，小心出行\n';
                } else if (weather.includes('晴')) {
                    advice += '   ☀️ 天气晴朗，适合出行\n';
                }

                // 湿度建议
                if (humidity > 80) {
                    advice += '   💧 湿度较高，注意通风\n';
                } else if (humidity < 30) {
                    advice += '   💧 空气干燥，注意补水\n';
                }
            }

            return advice;

        } catch (error) {
            console.error('生成天气建议失败:', error);
            return '\n💡 暂时无法提供出行建议';
        }
    }
}

module.exports = new WeatherController();